
<script>
import debounce from 'lodash/debounce';

export default {
  name: 'GoTop',

  data() {
    return {
      showBtn: false
    };
  },

  props: {
    // 设置按钮的大小
    size: {
      type: String,
      default: 'large'
    },
    // 设置按钮滚动到何处显示
    visibilityHeight: {
      type: Number,
      default: 200
    },
    // 设置监听滚动的DOM元素
    target: {
      type: Function,
      default: () => window
    }
  },

  created() {
    this.$nextTick(() => {
      const scroll = this.target();
      scroll.addEventListener('scroll', event => {
        const scrollTop = event.target.scrollTop;
        if (scrollTop >= this.visibilityHeight) {
          this.showBtn = true;
        } else {
          this.showBtn = false;
        }
      });
    })
  },

  computed: {

  },

  methods: {
    // 这里使用防抖进行优化处理
    goTop: debounce(function() {
      // 点击返回顶部,控制只有按钮显示才有效
      if (this.showBtn) {
        const scroll = this.target();
        scroll.scrollTo({
          left: 0,
          top: 0,
          behavior: 'smooth'
        });
      }
    })
  },

  render(h) {
    return h('div', {
      attrs: {
        id: 'go-top'
      }
    }, [
      // 按钮
      h('a-button', {
        staticClass: 'top-btn',
        attrs: {
          type: 'primary',
          shape: "circle",
          icon: "caret-up"
        },
        props: {
          size: this.size
        },
        on: {
          click: this.goTop
        },
        // 这里是可以通过自定义指令完成v-show
        directives: [
          {
            name: "show",
            rawName: "v-show",
            value: this.showBtn,
            expression: "this.showBtn",
          },
        ]
      })
    ])
  }
};
</script>

<style lang="less" scoped>
#go-top .top-btn {
  position: fixed;
  right: 40px;
  bottom: 130px;
  background-color: #F2F6FC;
  border: none;
  color: #ec4141;
}
</style>